406D - Hill Climbing - CodeForces Solution


dfs and similar geometry trees *2200

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;

#define int long long

struct Point {
  int x, y;

  Point() {}
  Point(int _x, int _y): x(_x), y(_y) {}
};

inline int ori(Point a, Point b, Point c) {
  Point ba = {a.x - b.x, a.y - b.y};
  Point bc = {c.x - b.x, c.y - b.y};
  int cross =  (ba.x * bc.y - ba.y * bc.x);

  if (cross == 0) return 0;
  if (cross > 0) return +1;
  return -1;
}

const int N = 1e5 + 5;

int n;
Point a[N];
vector<int> g[N];
int par[N][20], dep[N];

void dfs(int u) {
  for (int v: g[u]) {
    par[v][0] = u;
    dep[v] = dep[u] + 1;

    for (int i = 1; (1 << i) <= n; ++i) {
      par[v][i] = par[par[v][i - 1]][i - 1];
    }

    dfs(v);
  }
}

int lca(int u, int v) {
  if (dep[u] > dep[v]) swap(u, v);
  int d = dep[v] - dep[u];
  for (int i = 0; (1 << i) <= d; ++i) {
    if (d >> i & 1) v = par[v][i];
  }
  if (u == v) return u;

  for (int i = 17; ~i; --i) {
    if (par[u][i] != par[v][i]) {
      u = par[u][i];
      v = par[v][i];
    }
  }

  return par[u][0];
}

signed main() {
  cin.tie(nullptr)->sync_with_stdio(false);

  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> a[i].x >> a[i].y;

  vector<int> hull;
  hull.push_back(n);
  for (int i = n - 1, sz = 1; i; --i, ++sz) {
    while (sz >= 2 && ori(a[i], a[hull[sz - 1]], a[hull[sz - 2]]) < 0) {
      hull.pop_back();
      sz -= 1;
    }

    g[hull.back()].push_back(i);
    hull.push_back(i);
  }

  dfs(n);
  int m; cin >> m;
  while (m--) {
    int u, v; cin >> u >> v;
    cout << lca(u, v) << ' ';
  }
}


Comments

Submit
0 Comments
More Questions

1725G - Garage
1725B - Basketball Together
735A - Ostap and Grasshopper
1183B - Equalize Prices
1481A - Space Navigation
1437B - Reverse Binary Strings
1362B - Johnny and His Hobbies
1299A - Anu Has a Function
1111A - Superhero Transformation
954A - Diagonal Walking
39F - Pacifist frogs
1451C - String Equality
386A - Second-Price Auction
1690E - Price Maximization
282B - Painting Eggs
440A - Forgotten Episode
233B - Non-square Equation
628B - New Skateboard
262B - Roma and Changing Signs
755C - PolandBall and Forest
456B - Fedya and Maths
376B - IOU
1623B - Game on Ranges
1118A - Water Buying
1462C - Unique Number
301A - Yaroslav and Sequence
38A - Army
38C - Blinds
1197A - DIY Wooden Ladder
1717D - Madoka and The Corruption Scheme